package com.tuling.spring;

import com.tuling.UserService;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * 基于beanName的匹配规则作代理增强
 * {@link BeanNameAutoProxyCreator#setBeanNames(String...)}
 */
public class BeanNameAutoProxyCreatorDemo {

	@Bean
	public UserService userService(){
		return new UserService();
	}

	@Bean
	public MethodInterceptor testAroundAdvice() {
		return invocation -> {
			System.out.println("before...");
			Object result = invocation.proceed();
			System.out.println("after...");
			return result;
		};
	}

	@Bean
	public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
		BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
		beanNameAutoProxyCreator.setBeanNames("userSe*");
		beanNameAutoProxyCreator.setInterceptorNames("testAroundAdvice");
		beanNameAutoProxyCreator.setProxyTargetClass(true);
		return beanNameAutoProxyCreator;
	}

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanNameAutoProxyCreatorDemo.class);
		UserService userInterface = (UserService) context.getBean("userService");
		userInterface.test();
	}
}
